package com.bmf.admin.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.text.CharSequenceUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * exe运行工具
 *
 * @author 
 * @date 2023/02/20
 */
@Slf4j
public class RunExeUtil {
    /**
     * 跑
     *
     * @param exePath exe 路径
     * @param exeFile EXE 文件
     * @param command 命令
     * @return int
     * @throws IOException          IO异常
     * @throws InterruptedException 中断异常
     */
    public static int run(String exePath, String exeFile, List<String> command) throws IOException, InterruptedException {
        if (CharSequenceUtil.isBlank(exePath) || CharSequenceUtil.isBlank(exeFile)) {
            return -1;
        }
        String os = System.getProperty("os.name");
        List<String> commands = new ArrayList<>();
        Process process;
        int exitCode;
        if (os != null && os.toLowerCase().startsWith("linux")) {
            commands.add("sudo");
            commands.add("LD_LIBRARY_PATH=`pwd`;/usr/bin/env;");
            commands.add("./"+exeFile);
            commands.addAll(command);
            String cmd = String.join(" ", commands);
            log.info("开始调用外部程序：{}", cmd);
            ProcessBuilder processBuilder = new ProcessBuilder(commands);
            processBuilder.directory(new File(exePath).getCanonicalFile());
            processBuilder.inheritIO();
            process = processBuilder.start();
            exitCode = process.waitFor();
        } else {
            commands.add(exePath + exeFile);
            if (CollUtil.isNotEmpty(command)) {
                commands.addAll(command);
            }
            String cmd = String.join(" ", commands);
            log.info("开始调用外部程序：{}", cmd);
            ProcessBuilder processBuilder = new ProcessBuilder(commands);
            processBuilder.inheritIO(); //  因为mongodb 子进程退出异常。必须使用这个
            process = processBuilder.start();
            exitCode = process.waitFor();
        }
        // 如果子进程未在指定时间内完成，终止子进程
        if (!process.isAlive()) {
            process.destroy();
        }
        return exitCode;
    }
    /**
     * 跑
     *
     * @param exePath exe 路径
     * @param exeFile EXE 文件
     * @param command 命令
     * @return int
     * @throws IOException          IO异常
     * @throws InterruptedException 中断异常
     */
    public static int run(String exePath, String exeFile, String... command) throws IOException, InterruptedException {
        return run(exePath, exeFile, Arrays.asList(command));
    }
    /**
     * 打印exe
     * 因为mongodb 子进程退出异常。不能使用这个
     *
     * @param inputStream 输入流
     * @throws IOException ioexception
     */
    @Deprecated
    private static void printExe(InputStream inputStream) throws IOException {
        String line;
        try (BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream, Charset.defaultCharset()))) {
            while ((line = bufferedReader.readLine()) != null || (line = bufferedReader.readLine()).equals("-1")) {
                log.info("被调用程序输出：" + line);
            }
        } catch (IOException e) {
            log.error(ExceptionUtil.stacktraceToString(e));
            throw e;
        }
    }
}
